{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"float:right\"><i>Peter Norvig, 15 June 2015</i></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Let's Code About Bike Locks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The [June 15, 2015 post on Bike Snob NYC](http://bikesnobnyc.blogspot.com/2015/06/lets-get-this-show-on-road-once-we-all.html) leads with \"*Let's talk about bike locks.*\" Here's what I want to talk about: in my local bike shop, I saw a combination  lock called *WordLock&reg;*,\n",
    "which replaces digits  with  letters.   I classified this as a Fred lock,\n",
    "\"[Fred](http://bikesnobnyc.blogspot.com/2014/06/a-fred-too-far.html)\" being the term for an amateurish cyclist with the wrong equipment.\n",
    "I tried the combination \"FRED,\" and was amused with the result:\n",
    "\n",
    "![](http://norvig.com/ipython/fredbuns.jpg)\n",
    "\n",
    "FRED BUNS! Naturally I set all the other locks on the rack to FRED BUNS as well. But my curiosity was raised ... \n",
    "\n",
    "# Questions\n",
    "\n",
    "1. How many words can the WordLock&reg; make?\n",
    "3. Can a lock with different letters on the tumblers make more words? \n",
    "4. How many words can be made simultaneously? For example, with the tumbler set to \"FRED\", the lock\n",
    "above also makes \"BUNS\" in the next line, but with \"SOMN\", fails to make a word in the third line.\n",
    "Could different letters make words in every horizontal line?\n",
    "5. Is it a coincidence that the phrase \"FRED BUNS\" appears, or was it planted there by mischievous WordLock&reg; designers? \n",
    "\n",
    "Vocabulary\n",
    "===\n",
    "\n",
    "Before we can answer the questions, we'll need to be clear about the vocabulary of the problem and how to represent concepts in code:\n",
    "\n",
    "* **Lock**: For our purposes a lock can be modeled as a `list` of 4 **tumblers**. \n",
    "* **Tumbler:** Each tumbler has  10 distinct letters. I will represent a tumbler as a `str` of 10 letters.\n",
    "* **Combination**: Choosing a letter from each tumbler gives a combination, such as \"FRED\" or \"BUNS\". There are 4<sup>10</sup> = 10,000 combinations.\n",
    "* **Word**: Some combinations (such as \"BUNS\") are *words*; others (such as \"SOMN\") are not words. We'll need a collection of dictionary words.\n",
    "\n",
    "Now on to the code!  First the imports I will need and the vocabulary concepts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from   __future__ import division, print_function # To work in Python 2.x or 3.x\n",
    "from   collections import Counter, defaultdict\n",
    "import itertools\n",
    "import random \n",
    "\n",
    "Lock     = list     # A Lock is a list of tumblers\n",
    "Tumbler  = ''.join  # A Tumbler is 10 characters joined into a str\n",
    "Word     = ''.join  # A word is 4 letters joined into a str"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The only remaining vocabulary concept is `combinations`. I will define `fredbuns` to be a lock with four tumblers, but with each tumbler consisting of not all ten letters, but only the two letters that spell \"FRED BUNS\": "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fredbuns = ['FB', 'RU', 'EN', 'DS'] # A lock with two letters on each of four tumblers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We need a way to get the combinations that can be made from this lock.  It turns out that the built-in function `itertools.product` does most of the job; it generates the product of all 2 &times; 2 &times; 2 &times; 2 = 16 combinations of letters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('F', 'R', 'E', 'D'),\n",
       " ('F', 'R', 'E', 'S'),\n",
       " ('F', 'R', 'N', 'D'),\n",
       " ('F', 'R', 'N', 'S'),\n",
       " ('F', 'U', 'E', 'D'),\n",
       " ('F', 'U', 'E', 'S'),\n",
       " ('F', 'U', 'N', 'D'),\n",
       " ('F', 'U', 'N', 'S'),\n",
       " ('B', 'R', 'E', 'D'),\n",
       " ('B', 'R', 'E', 'S'),\n",
       " ('B', 'R', 'N', 'D'),\n",
       " ('B', 'R', 'N', 'S'),\n",
       " ('B', 'U', 'E', 'D'),\n",
       " ('B', 'U', 'E', 'S'),\n",
       " ('B', 'U', 'N', 'D'),\n",
       " ('B', 'U', 'N', 'S')]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(itertools.product(*fredbuns))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "I would prefer to deal with the string `'BUNS'` rather than the tuple `('B', 'U', 'N', 'S')`, so I will define a function, `combinations`, that takes a lock as input and returns a list of strings representing the combinations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def combinations(lock):\n",
    "    \"Return a list of all combinations that can be made by this lock.\"\n",
    "    return [Word(combo) for combo in itertools.product(*lock)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['FRED',\n",
       " 'FRES',\n",
       " 'FRND',\n",
       " 'FRNS',\n",
       " 'FUED',\n",
       " 'FUES',\n",
       " 'FUND',\n",
       " 'FUNS',\n",
       " 'BRED',\n",
       " 'BRES',\n",
       " 'BRND',\n",
       " 'BRNS',\n",
       " 'BUED',\n",
       " 'BUES',\n",
       " 'BUND',\n",
       " 'BUNS']"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "combinations(fredbuns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Dictionary Words\n",
    "===\n",
    "\n",
    "I happen to have handy a file of four-letter words (no, not *[that](http://en.wikipedia.org/wiki/Four-letter_word)* kind of four-letter word). It is the union of an official Scrabble&reg; word list and a list of proper names. The following shell command tests if the file has already been downloaded to our local directory and if not, fetches it from the web:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "! [ -e words4.txt ] || curl -O http://norvig.com/ngrams/words4.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here are the first few lines of the file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AADI\r\n",
      "AAHS\r\n",
      "AALS\r\n",
      "ABAS\r\n",
      "ABBA\r\n",
      "ABBE\r\n",
      "ABBY\r\n",
      "ABED\r\n",
      "ABEL\r\n",
      "ABET\r\n"
     ]
    }
   ],
   "source": [
    "! head words4.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python can make a set of words:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "WORDS = set(open('words4.txt').read().split())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4360"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(WORDS)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So that means that no lock could ever make more than 4,360 words.  Let's define `words_from(lock)`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def words_from(lock): \n",
    "    \"A list of words that can be made by lock.\"\n",
    "    return [c for c in combinations(lock) if c in WORDS]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['FRED', 'FUND', 'FUNS', 'BRED', 'BUND', 'BUNS']"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "words_from(fredbuns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Note*: An alternative is to represent a collection of words as a `set`; then `words_from` could do `return combinations(lock) & WORDS`. \n",
    "\n",
    "I will also introduce the function `show` to print out a lock and its words:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def show(lock):\n",
    "    \"Show a lock and the words it makes.\"\n",
    "    words = words_from(lock)\n",
    "    print('Lock:  {}\\nCount: {}\\nWords: {}'\n",
    "          .format(space(lock), len(words), space(sorted(words))))\n",
    "    \n",
    "space = ' '.join  # Function to concatenate strings with a space between each one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lock:  FB RU EN DS\n",
      "Count: 6\n",
      "Words: BRED BUND BUNS FRED FUND FUNS\n"
     ]
    }
   ],
   "source": [
    "show(fredbuns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For this tiny lock with just two letters on each tumbler, we find that 6 out of the 16 possible combinations are words. We're now ready to answer the real questions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Question 1: How Many Words?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is the answer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "wordlock = ['SPHMTWDLFB', 'LEYHNRUOAI', 'ENMLRTAOSK', 'DSNMPYLKTE']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lock:  SPHMTWDLFB LEYHNRUOAI ENMLRTAOSK DSNMPYLKTE\n",
      "Count: 1118\n",
      "Words: BAAL BAAS BAKE BALD BALE BALK BALL BALM BALS BAMS BAND BANE BANK BANS BARD BARE BARK BARM BARN BARS BASE BASK BASS BAST BATE BATS BATT BEAD BEAK BEAM BEAN BEAT BEEN BEEP BEES BEET BELL BELS BELT BEND BENE BENS BENT BERK BERM BEST BETS BIAS BIKE BILE BILK BILL BIND BINE BINS BINT BIOS BIRD BIRK BIRL BISE BISK BITE BITS BITT BLAE BLAM BLAT BLED BLET BLOT BOAS BOAT BOLD BOLE BOLL BOLT BOND BONE BONK BONY BOOK BOOM BOON BOOS BOOT BORE BORK BORN BORT BOSK BOSS BOTS BOTT BRAD BRAE BRAN BRAS BRAT BRAY BRED BREE BREN BROS BULK BULL BUMP BUMS BUND BUNK BUNN BUNS BUNT BUOY BURD BURL BURN BURP BURS BURY BUSK BUSS BUST BUSY BUTE BUTS BUTT BYES BYRE BYRL BYTE DAKS DALE DALS DAME DAMN DAMP DAMS DANE DANK DANS DARE DARK DARN DART DATE DEAD DEAL DEAN DEED DEEM DEEP DEES DEET DEKE DELE DELL DELS DELT DEME DEMY DENE DENS DENT DENY DEON DERE DERM DESK DHAK DHAL DIAL DIED DIEL DIES DIET DIKE DILL DIME DIMS DINE DINK DINS DINT DIOL DION DIRE DIRK DIRL DIRT DISK DISS DITE DITS DOAT DOES DOLE DOLL DOLS DOLT DOME DOMS DONE DONS DOOM DORE DORK DORM DORP DORS DORY DOSE DOSS DOST DOTE DOTS DOTY DRAM DRAT DRAY DREE DREK DROP DUAD DUAL DUEL DUES DUET DUKE DULL DULY DUMP DUNE DUNK DUNS DUNT DUOS DURE DURN DUSK DUST DUTY DYAD DYED DYES DYKE DYNE FAKE FALL FAME FANE FANS FARD FARE FARL FARM FART FAST FATE FATS FEAL FEAT FEED FEEL FEES FEET FELL FELT FEME FEMS FEND FENS FEOD FERE FERN FESS FEST FETE FETS FIAT FILE FILL FILM FILS FIND FINE FINK FINN FINS FIRE FIRM FIRN FIRS FIST FITS FLAK FLAM FLAN FLAP FLAT FLAY FLED FLEE FLEY FLOE FLOP FOAL FOAM FOES FOLD FOLK FOND FONS FONT FOOD FOOL FOOT FORD FORE FORK FORM FORT FOSS FRAE FRAP FRAT FRAY FRED FREE FRET FROE FROM FUEL FULL FUME FUMY FUND FUNK FUNS FURL FURS FURY FUSE FUSS FYKE HAED HAEM HAEN HAES HAET HAKE HALE HALL HALM HALT HAME HAMS HAND HANK HANS HANT HARD HARE HARK HARL HARM HARP HART HASP HAST HATE HATS HEAD HEAL HEAP HEAT HEED HEEL HELD HELL HELM HELP HEME HEMP HEMS HENS HENT HERD HERE HERL HERM HERN HERS HEST HETS HIED HIES HIKE HILL HILT HIMS HIND HINS HINT HIRE HISN HISS HIST HITS HOED HOES HOKE HOLD HOLE HOLK HOLM HOLP HOLS HOLT HOLY HOME HOMY HONE HONK HONS HOOD HOOK HOOP HOOT HORN HOSE HOST HOTS HUED HUES HULK HULL HUMP HUMS HUNK HUNS HUNT HURL HURT HUSK HUTS HYMN HYTE LAKE LAKY LALL LAME LAMP LAMS LAND LANE LANK LARD LARK LARS LASE LASS LAST LATE LATS LEAD LEAK LEAL LEAN LEAP LEAS LEEK LEES LEET LEKE LEKS LEND LENS LENT LEON LESS LEST LETS LIAM LIAN LIED LIEN LIES LIKE LILT LILY LIME LIMN LIMP LIMY LINE LINK LINN LINS LINT LINY LION LIRE LISP LIST LITE LITS LOAD LOAM LOAN LOLL LONE LOOK LOOM LOON LOOP LOOS LOOT LORD LORE LORN LORY LOSE LOSS LOST LOTS LUES LUKE LULL LUMP LUMS LUNE LUNK LUNT LUNY LURE LURK LUST LUTE LYAM LYES LYLE LYRE LYSE MAES MAKE MALE MALL MALM MALT MANE MANS MANY MARE MARK MARL MARS MART MARY MASK MASS MAST MATE MATS MATT MEAD MEAL MEAN MEAT MEED MEEK MEET MELD MELL MELS MELT MEME MEMS MEND MERE MERK MERL MESS METE MHOS MIEN MIKE MILD MILE MILK MILL MILS MILT MIME MIND MINE MINK MINT MIRE MIRK MIRS MIRY MISE MISS MIST MITE MITT MITY MOAN MOAS MOAT MOKE MOLD MOLE MOLL MOLS MOLT MOLY MOME MOMS MONK MONS MONY MOOD MOOL MOON MOOS MOOT MORE MORN MORS MORT MOSK MOSS MOST MOTE MOTS MOTT MULE MULL MUMM MUMP MUMS MUNS MUON MURE MURK MUSE MUSK MUSS MUST MUTE MUTS MUTT PALE PALL PALM PALP PALS PALY PAMS PANE PANS PANT PARD PARE PARK PARS PART PASE PASS PAST PATE PATS PATY PEAK PEAL PEAN PEAS PEAT PEED PEEK PEEL PEEN PEEP PEES PEKE PELE PELT PEND PENS PENT PEON PERE PERK PERM PERP PERT PEST PETS PHAT PHON PHOT PIAL PIAN PIAS PIED PIES PIKE PILE PILL PILY PIMP PINE PINK PINS PINT PINY PION PIRN PISS PITS PITY PLAN PLAT PLAY PLED PLOD PLOP PLOT PLOY POEM POET POKE POKY POLE POLL POLS POLY POME POMP POMS POND PONE PONS PONY POOD POOL POON POOP POOS PORE PORK PORN PORT POSE POST POSY POTS PRAM PRAT PRAY PREE PREP PREY PROD PROM PROP PROS PUKE PULE PULL PULP PULS PUMP PUNK PUNS PUNT PUNY PURE PURL PURS PUSS PUTS PUTT PYAS PYES PYRE SAAD SAKE SALE SALL SALP SALS SALT SAME SAMP SAND SANE SANK SANS SARD SARK SASS SATE SEAL SEAM SEAN SEAS SEAT SEED SEEK SEEL SEEM SEEN SEEP SEES SELL SELS SEME SEND SENE SENT SERE SERS SETS SETT SHAD SHAE SHAM SHAT SHAY SHED SHES SHOD SHOE SHOP SHOT SIAL SIKE SILD SILK SILL SILT SIMP SIMS SINE SINK SINS SIRE SIRS SITE SITS SLAM SLAP SLAT SLAY SLED SLOE SLOP SLOT SNAP SNED SNOT SOAK SOAP SOKE SOLD SOLE SOLS SOME SOMS SONE SONS SOOK SOON SOOT SORD SORE SORN SORT SOTS SUED SUES SUET SUKS SULK SUMP SUMS SUNK SUNN SUNS SURD SURE SUSS SYED SYKE SYNE TAEL TAKE TALE TALK TALL TAME TAMP TAMS TANK TANS TAOS TARE TARN TARP TARS TART TASK TASS TATE TATS TEAK TEAL TEAM TEAS TEAT TEED TEEL TEEM TEEN TEES TELE TELL TELS TEMP TEND TENS TENT TERM TERN TESS TEST TETS THAE THAN THAT THEE THEM THEN THEY TIED TIES TIKE TILE TILL TILS TILT TIME TINE TINS TINT TINY TIRE TIRL TITS TOAD TOED TOES TOKE TOLD TOLE TOLL TOME TOMS TONE TONS TONY TOOK TOOL TOOM TOON TOOT TORE TORN TORS TORT TORY TOSS TOST TOTE TOTS TRAD TRAE TRAM TRAP TRAY TREE TREK TRES TRET TREY TROD TROP TROT TROY TULE TUMP TUNE TUNS TURD TURK TURN TUSK TUTS TYEE TYES TYKE TYNE TYRE WAES WAKE WALE WALK WALL WALY WAME WAND WANE WANK WANS WANT WANY WARD WARE WARK WARM WARN WARP WARS WART WARY WASP WAST WATS WATT WEAK WEAL WEAN WEED WEEK WEEL WEEN WEEP WEES WEET WELD WELL WELT WEND WENS WENT WERE WERT WEST WETS WHAM WHAP WHAT WHEE WHEN WHET WHEY WHOM WHOP WILD WILE WILL WILT WILY WIMP WIND WINE WINK WINS WINY WIRE WIRY WISE WISP WISS WIST WITE WITS WOAD WOES WOKE WOKS WOLD WONK WONS WONT WOOD WOOL WOOS WORD WORE WORK WORM WORN WORT WOST WOTS WRAP WREN WUSS WYES WYLE WYND WYNN WYNS WYTE\n"
     ]
    }
   ],
   "source": [
    "show(wordlock)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How Secure is WordLock?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The lock makes 1118 words (according to my word list).  You might say that an attacker who knows the combination is a word would find this lock to be only 11.18% as secure as a 4-digit lock with 10,000 combinations.  But in reality, every cable lock is [vulnerable](https://www.sfbike.org/news/video-how-to-lock-your-bike/) to an attacker with wire  cutters, or with a knowledge of lock-picking, so  security is equally poor for WordLock&reg; and for an equivalent lock with numbers. (You should use a hardened steel U-lock instead.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Random Locks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Question 2 asks if a different lock can make more words.  As a baseline, before we get to improved locks, I will start with completely random locks, as produced by the function `random_lock`. I use `t=4` to say that by default there are 4 tumblers, and `c=10` to indicate 10 letters on each tumbler (\"c\" for \"circumference\"). I give `random_lock` an argument to seed the random number generator; that makes calls repeatable if desired."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def random_lock(t=4, c=10, seed='seed'):\n",
    "    \"Make a lock by sampling randomly and uniformly from the alphabet.\"\n",
    "    random.seed(seed)\n",
    "    return Lock(Tumbler(random.sample(alphabet, c))\n",
    "                for i in range(t))\n",
    "\n",
    "alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lock:  EBHLJPYKQR VNSYPCWBGR BJOHSCFMRP XCSLUNMQJI\n",
      "Count: 15\n",
      "Words: BROS BYRL EBBS EBON ECRU EGOS ENOL EPOS EROS ERRS HYMN HYPS KNOX PROM PROS\n"
     ]
    }
   ],
   "source": [
    "show(random_lock())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Wow, that's not very many words. Let's repeat 100 times and take the best one, with \"best\" determined by the function `word_count`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def word_count(lock): return len(words_from(lock))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lock:  IDQPSFOJCW MQYGODAINT NLRZPXWFBI STGWCOLJEH\n",
      "Count: 259\n",
      "Words: CABS CAFE CALE CALL CALO CANE CANS CANT CAPE CAPH CAPO CAPS CARE CARL CARS CART CAWS CINE CIRE COBS COFT COIL COLE COLS COLT CONE CONS COPE COPS CORE CORS COWL COWS DABS DAFT DAIS DALE DALS DANE DANG DANS DAPS DARE DART DAWS DAWT DAZE DIBS DIFS DILL DINE DING DINO DINS DINT DIPS DIPT DIRE DIRL DIRT DOIT DOLE DOLL DOLS DOLT DONE DONG DONS DOPE DORE DORS DOWS DOZE DYNE FABS FAIL FALL FANE FANG FANO FANS FARE FARL FARO FART FAZE FIBS FIFE FILE FILL FILO FILS FINE FINO FINS FIRE FIRS FIXT FOBS FOIL FONS FONT FOPS FORE FORT FOWL IDLE IMPS INFO INNS INRO IONS JABS JAIL JANE JAPE JARL JARS JAWS JIBE JIBS JILL JILT JINS JOBS JOLE JOLT JOWL JOWS OAFS OARS ODIC OGLE OGRE OILS OMIT OOPS OOZE OTIC OTIS PAIL PALE PALL PALS PANE PANG PANS PANT PAPS PARE PARS PART PAWL PAWS PILE PILL PINE PING PINS PINT PIPE PIPS POIS POLE POLL POLO POLS PONE PONG PONS POPE POPS PORE PORT POWS PYIC PYRE PYRO QOPH SABE SABS SAFE SAIL SALE SALL SALS SALT SANE SANG SANS SAPS SAWS SIBS SIFT SILL SILO SILT SINE SING SINH SINS SIPE SIPS SIRE SIRS SIZE SMIT SNIT SOBS SOFT SOIL SOLE SOLO SOLS SONE SONG SONS SOPH SOPS SORE SORT SOWS SYBO SYNC SYNE SYPH WABS WAFT WAIL WAIT WALE WALL WANE WANS WANT WAPS WARE WARS WART WAWL WAWS WIFE WILE WILL WILT WINE WING WINO WINS WIPE WIRE WONS WONT WOPS WORE WORT WOWS WYLE WYNS\n"
     ]
    }
   ],
   "source": [
    "random_locks = [random_lock(seed=i) for i in range(100)]\n",
    "\n",
    "show(max(random_locks, key=word_count))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Still not very good.  We will need a more systematic approach."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Question 2: More Words (via Greedy Locks)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "My first idea for a lock with more words is this: consider each tumbler, one at a time, and fill the tumbler with the letters that make the most words.  How do I determine what letters make the most words?  A `Counter` does most of the work; we feed it a list of the first letter of each word, and then ask it for the ten most common letters (and their counts): "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('S', 373),\n",
       " ('T', 268),\n",
       " ('P', 268),\n",
       " ('B', 267),\n",
       " ('D', 251),\n",
       " ('C', 248),\n",
       " ('L', 246),\n",
       " ('M', 239),\n",
       " ('A', 236),\n",
       " ('R', 203)]"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "first_letters = [w[0] for w in WORDS]\n",
    "\n",
    "Counter(first_letters).most_common(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In other words, the letters SPTBDCLMAR are the most common ways to start a word. Let's add up those counts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2599"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def n_most_common(counter, n): return sum(n for (_, n) in counter.most_common(n))\n",
    "\n",
    "n_most_common(Counter(first_letters), 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This means that SPTBDCLMAR covers 2,599 words. We don't know for sure that these are the best 10 letters to put on the first tumbler, but we do know that whatever letters are best, they can't form more than 2,599 words, so we have an upper bound on the number of words in a lock (and the 1,118 from `wordlock` is a lower bound).\n",
    "\n",
    "What letters should we put on the second tumbler?  We will do the same thing, but this time don't consider *all* the words in the dictionary; just consider the 2,599 words that start with one of the ten letters on the first tumbler.  Continue this way until we fill in all four tumblers. This is called a *greedy* approach, because when we consider each tumbler, we pick the solution that looks best right then, for that tumbler, without consideration for future tumblers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def greedy_lock(t=4, c=10, words=WORDS):\n",
    "    \"Make a lock with t tumblers, each consisting of the c letters that cover the most words at that position.\"\n",
    "    lock = Lock()\n",
    "    for i in range(t):\n",
    "        # Make a tumbler of c letters, such that the tumbler covers the most words.\n",
    "        # Then update words to only include the ones that can be made with this tumbler\n",
    "        counter = Counter(word[i] for word in words)\n",
    "        tumbler = Tumbler(L for (L, _) in counter.most_common(c))\n",
    "        words   = [w for w in words if w[i] in tumbler]\n",
    "        lock.append(tumbler)\n",
    "    return lock"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lock:  STPBDCLMAR OAIEURLHYN RNALEOTISM SETADNLKPY\n",
      "Count: 1177\n",
      "Words: AALS AEON AERY AHED AHIS AHOY AILA AILS AIMS AINS AIRN AIRS AIRT AIRY AITS ALAE ALAN ALAS ALEA ALEE ALEK ALES ALIA ALIT ALLS ALLY ALMA ALME ALMS ALOE ALTS ANAL ANAS ANAY ANES ANIL ANIS ANNA ANNE ANOA ANON ANSA ANTA ANTE ANTS ARAK AREA ARES ARIA ARID ARIE ARIL ARMS ARMY ARON ARSE ARTS ARTY AULD AUNT AURA AYAN AYES AYIN AYLA BAAL BAAS BAIL BAIT BALD BALE BALK BALL BALS BAMS BAND BANE BANK BANS BARD BARE BARK BARN BARS BASE BASK BASS BAST BATE BATS BATT BEAD BEAK BEAN BEAT BEEN BEEP BEES BEET BELL BELS BELT BEMA BEND BENE BENS BENT BERK BEST BETA BETS BIAS BILE BILK BILL BIMA BIND BINE BINS BINT BIOS BIRD BIRK BIRL BISE BISK BITE BITS BITT BLAE BLAT BLED BLET BLIN BLIP BLOT BOAS BOAT BOIL BOLA BOLD BOLE BOLL BOLT BOND BONE BONK BONY BOOK BOON BOOS BOOT BORA BORE BORK BORN BORT BOSK BOSS BOTA BOTS BOTT BRAD BRAE BRAN BRAS BRAT BRAY BREA BRED BREE BREN BRIA BRIE BRIN BRIS BRIT BROS BULK BULL BUMP BUMS BUNA BUND BUNK BUNN BUNS BUNT BUOY BURA BURD BURL BURN BURP BURS BURY BUSK BUSS BUST BUSY BUTE BUTS BUTT BYES BYRE BYRL BYTE CAEL CAID CAIN CALE CALK CALL CAME CAMP CAMS CANE CANS CANT CARA CARD CARE CARK CARL CARN CARP CARS CART CASA CASE CASK CAST CATE CATS CEES CEIL CELL CELS CELT CENT CERE CESS CETE CHAD CHAP CHAT CHAY CHIA CHID CHIN CHIP CHIS CHIT CHON CHOP CIAN CINE CION CIRE CIST CITE CITY CLAD CLAN CLAP CLAY CLIP CLOD CLON CLOP CLOT CLOY COAL COAT COED COEN COIL COIN COLA COLD COLE COLS COLT COLY COMA COME COMP CONE CONK CONN CONS CONY COOK COOL COON COOP COOS COOT CORA CORD CORE CORK CORN CORS CORY COSS COST COSY COTE COTS CRAP CRED CRIS CRIT CROP CUED CUES CULL CULT CUNT CURD CURE CURL CURN CURS CURT CUSK CUSP CUSS CUTE CUTS CYAN CYMA CYME CYST DAIS DALE DALS DAME DAMN DAMP DAMS DANA DANE DANK DANS DARE DARK DARN DART DATA DATE DEAD DEAL DEAN DEED DEEP DEES DEET DEIL DELE DELL DELS DELT DEME DEMY DENE DENS DENT DENY DEON DERE DESK DHAK DHAL DIAL DIED DIEL DIES DIET DILL DIME DIMS DINA DINE DINK DINS DINT DIOL DION DIRE DIRK DIRL DIRT DISK DISS DITA DITE DITS DOAT DOES DOIT DOLE DOLL DOLS DOLT DOME DOMS DONA DONE DONS DORE DORK DORP DORS DORY DOSE DOSS DOST DOTE DOTS DOTY DRAT DRAY DREE DREK DRIP DROP DUAD DUAL DUEL DUES DUET DUIT DULL DULY DUMA DUMP DUNE DUNK DUNS DUNT DUOS DURA DURE DURN DUSK DUST DUTY DYAD DYED DYES DYNE LAID LAIN LALL LAMA LAME LAMP LAMS LANA LAND LANE LANK LARA LARD LARK LARS LASE LASS LAST LATE LATS LEAD LEAK LEAL LEAN LEAP LEAS LEEK LEES LEET LEIA LEIS LELA LENA LEND LENS LENT LEON LESS LEST LETS LIAN LIED LIEN LIES LILA LILT LILY LIMA LIME LIMN LIMP LIMY LINA LINE LINK LINN LINS LINT LINY LION LIRA LIRE LISA LISP LIST LITE LITS LOAD LOAN LOID LOIN LOLA LOLL LONE LOOK LOON LOOP LOOS LOOT LORD LORE LORN LORY LOSE LOSS LOST LOTA LOTS LUES LUIS LULL LUMA LUMP LUMS LUNA LUNE LUNK LUNT LUNY LURE LURK LUST LUTE LYES LYLA LYLE LYRA LYRE LYSE MAES MAIA MAID MAIL MAIN MALE MALL MALT MAMA MANA MANE MANS MANY MARA MARE MARK MARL MARS MART MARY MASA MASK MASS MAST MATE MATS MATT MEAD MEAL MEAN MEAT MEED MEEK MEET MELD MELL MELS MELT MEME MEMS MEND MERE MERK MERL MESA MESS META METE MHOS MIEN MILA MILD MILE MILK MILL MILS MILT MIME MINA MIND MINE MINK MINT MIRA MIRE MIRK MIRS MIRY MISE MISS MIST MITE MITT MITY MOAN MOAS MOAT MOIL MOLA MOLD MOLE MOLL MOLS MOLT MOLY MOME MOMS MONA MONK MONS MONY MOOD MOOL MOON MOOS MOOT MORA MORE MORN MORS MORT MOSK MOSS MOST MOTE MOTS MOTT MULE MULL MUMP MUMS MUNS MUON MURA MURE MURK MUSA MUSE MUSK MUSS MUST MUTE MUTS MUTT MYLA MYNA MYRA PAID PAIK PAIL PAIN PALE PALL PALP PALS PALY PAMS PANE PANS PANT PARA PARD PARE PARK PARS PART PASE PASS PAST PATE PATS PATY PEAK PEAL PEAN PEAS PEAT PEED PEEK PEEL PEEN PEEP PEES PEIN PELE PELT PEND PENS PENT PEON PERE PERK PERP PERT PEST PETS PHAT PHIS PHON PHOT PIAL PIAN PIAS PIED PIES PILE PILL PILY PIMA PIMP PINA PINE PINK PINS PINT PINY PION PIRN PISS PITA PITS PITY PLAN PLAT PLAY PLEA PLED PLIE PLOD PLOP PLOT PLOY POET POIS POLE POLL POLS POLY POME POMP POMS POND PONE PONS PONY POOD POOL POON POOP POOS PORE PORK PORN PORT POSE POST POSY POTS PRAT PRAY PREE PREP PREY PROA PROD PROP PROS PULA PULE PULL PULP PULS PUMA PUMP PUNA PUNK PUNS PUNT PUNY PURE PURL PURS PUSS PUTS PUTT PYAS PYES PYIN PYRE RAIA RAID RAIL RAIN RAIS RALE RAMP RAMS RAND RANK RANT RARE RASE RASP RATE RATS READ REAL REAP REED REEK REEL REES REID REIN REIS RELY REMS REMY REND RENE RENT REST RETE RETS RHEA RHOS RIAL RIAN RIAS RIEL RILE RILL RIME RIMS RIMY RIND RINK RINS RIOT RISE RISK RITA RITE ROAD ROAN ROES ROIL ROLE ROLL ROME ROMP ROMS ROOD ROOK ROOT RORY ROSA ROSE ROSS ROSY ROTA ROTE ROTL ROTS RUED RUES RUIN RULE RULY RUMP RUMS RUNE RUNS RUNT RUSE RUSK RUST RUTS RYAN RYAS RYES RYND RYOT SAAD SAID SAIL SAIN SALE SALL SALP SALS SALT SAME SAMP SANA SAND SANE SANK SANS SARA SARD SARK SASS SATE SEAL SEAN SEAS SEAT SEED SEEK SEEL SEEN SEEP SEES SEIS SELL SELS SEME SEND SENE SENT SERA SERE SERS SETA SETS SETT SHAD SHAE SHAT SHAY SHEA SHED SHES SHIN SHIP SHIT SHOD SHOE SHOP SHOT SIAL SILD SILK SILL SILT SIMA SIMP SIMS SINE SINK SINS SIRE SIRS SITE SITS SLAP SLAT SLAY SLED SLID SLIP SLIT SLOE SLOP SLOT SNAP SNED SNIP SNIT SNOT SOAK SOAP SOIL SOLA SOLD SOLE SOLS SOMA SOME SOMS SONE SONS SOOK SOON SOOT SORA SORD SORE SORN SORT SOTS SRIS SUED SUES SUET SUIT SULK SUMP SUMS SUNK SUNN SUNS SURA SURD SURE SUSS SYED SYNE TAEL TAIL TAIN TALA TALE TALK TALL TAME TAMP TAMS TANK TANS TAOS TARA TARE TARN TARP TARS TART TASK TASS TATE TATS TEAK TEAL TEAS TEAT TEED TEEL TEEN TEES TELA TELE TELL TELS TEMP TEND TENS TENT TERN TESS TEST TETS THAE THAN THAT THEA THEE THEN THEY THIN THIS TIED TIES TILE TILL TILS TILT TIME TINA TINE TINS TINT TINY TIRE TIRL TITS TOAD TOEA TOED TOES TOIL TOIT TOLA TOLD TOLE TOLL TOME TOMS TONE TONS TONY TOOK TOOL TOON TOOT TORA TORE TORN TORS TORT TORY TOSS TOST TOTE TOTS TRAD TRAE TRAP TRAY TREE TREK TRES TRET TREY TRIP TROD TROP TROT TROY TUIS TULE TUMP TUNA TUNE TUNS TURD TURK TURN TUSK TUTS TYEE TYES TYIN TYNE TYRE\n"
     ]
    }
   ],
   "source": [
    "show(greedy_lock())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Remember that the `wordlock` gave 1118 words, so the greedy lock with 1177 is better, but only by 5%. Is it possible to do better still?  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Question 2: More Words (via Improved Locks)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's another idea to get more words from a lock:\n",
    "\n",
    "1. Start with some lock.\n",
    "2. Pick, at random, one letter on one tumbler and change it to a new letter.\n",
    "3. If the change yields more words, keep the change; otherwise discard the change.\n",
    "4. Repeat.\n",
    "\n",
    "We can implement this strategy with the function `improved_lock`, which calls `changed_lock` to make a random change:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def improved_lock(lock, steps=3000):\n",
    "    \"Randomly change letters in lock, keeping changes that improve the score.\"\n",
    "    score = word_count(lock)\n",
    "    for i in range(steps):\n",
    "        lock2  = changed_lock(lock)\n",
    "        score2 = word_count(lock2)\n",
    "        if score2 >= score:   \n",
    "            lock, score = lock2, score2\n",
    "    return lock\n",
    "\n",
    "def changed_lock(lock): \n",
    "    \"Change one letter in one tumbler.\"\n",
    "    lock2 = Lock(lock)\n",
    "    i     = random.randrange(len(lock))\n",
    "    old   = random.choice(lock[i])\n",
    "    new   = random.choice([L for L in alphabet if L not in lock[i]])\n",
    "    lock2[i] = lock2[i].replace(old, new)\n",
    "    return lock2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see how this does to improve the best lock we've seen so far, the greedy lock:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lock:  STPBDCLMWF OAIEURLHYP RNALEOTISC SETADNLKHY\n",
      "Count: 1240\n",
      "Words: BAAL BAAS BACH BACK BAIL BAIT BALD BALE BALK BALL BALS BAND BANE BANK BANS BARD BARE BARK BARN BARS BASE BASH BASK BASS BAST BATE BATH BATS BATT BEAD BEAK BEAN BEAT BECK BEEN BEES BEET BELL BELS BELT BEND BENE BENS BENT BERK BEST BETA BETH BETS BIAS BICE BILE BILK BILL BIND BINE BINS BINT BIOS BIRD BIRK BIRL BISE BISK BITE BITS BITT BLAE BLAH BLAT BLED BLET BLIN BLOT BOAS BOAT BOCK BOIL BOLA BOLD BOLE BOLL BOLT BOND BONE BONK BONY BOOK BOON BOOS BOOT BORA BORE BORK BORN BORT BOSH BOSK BOSS BOTA BOTH BOTS BOTT BRAD BRAE BRAN BRAS BRAT BRAY BREA BRED BREE BREN BRIA BRIE BRIN BRIS BRIT BROS BUCK BULK BULL BUNA BUND BUNK BUNN BUNS BUNT BUOY BURA BURD BURL BURN BURS BURY BUSH BUSK BUSS BUST BUSY BUTE BUTS BUTT BYES BYRE BYRL BYTE CACA CAEL CAID CAIN CALE CALK CALL CANE CANS CANT CARA CARD CARE CARK CARL CARN CARS CART CASA CASE CASH CASK CAST CATE CATS CECA CEES CEIL CELL CELS CELT CENT CERE CESS CETE CHAD CHAT CHAY CHIA CHID CHIN CHIS CHIT CHON CIAN CINE CION CIRE CIST CITE CITY CLAD CLAN CLAY CLOD CLON CLOT CLOY COAL COAT COCA COCK COED COEN COIL COIN COLA COLD COLE COLS COLT COLY CONE CONK CONN CONS CONY COOK COOL COON COOS COOT CORA CORD CORE CORK CORN CORS CORY COSH COSS COST COSY COTE COTS CRED CRIS CRIT CUED CUES CULL CULT CUNT CURD CURE CURL CURN CURS CURT CUSK CUSS CUTE CUTS CYAN CYST DACE DAIS DALE DALS DANA DANE DANK DANS DARE DARK DARN DART DASH DATA DATE DEAD DEAL DEAN DECK DEED DEES DEET DEIL DELE DELL DELS DELT DENE DENS DENT DENY DEON DERE DESK DHAK DHAL DIAL DICE DICK DIED DIEL DIES DIET DILL DINA DINE DINK DINS DINT DIOL DION DIRE DIRK DIRL DIRT DISH DISK DISS DITA DITE DITS DOAT DOCK DOCS DOES DOIT DOLE DOLL DOLS DOLT DONA DONE DONS DORE DORK DORS DORY DOSE DOSS DOST DOTE DOTH DOTS DOTY DRAT DRAY DREE DREK DUAD DUAL DUCE DUCK DUCT DUEL DUES DUET DUIT DULL DULY DUNE DUNK DUNS DUNT DUOS DURA DURE DURN DUSK DUST DUTY DYAD DYED DYES DYNE FACE FACT FAIL FAIN FALL FANE FANS FARD FARE FARL FART FASH FAST FATE FATS FEAL FEAT FECK FEED FEEL FEES FEET FELL FELT FEND FENS FEOD FERE FERN FESS FEST FETA FETE FETS FIAT FICE FILA FILE FILL FILS FIND FINE FINK FINN FINS FIRE FIRN FIRS FISH FIST FITS FLAK FLAN FLAT FLAY FLEA FLED FLEE FLEY FLIT FLOE FOAL FOES FOIL FOIN FOLD FOLK FOND FONS FONT FOOD FOOL FOOT FORA FORD FORE FORK FORT FOSS FRAE FRAT FRAY FRED FREE FRET FRIT FROE FUCK FUEL FULL FUND FUNK FUNS FURL FURS FURY FUSE FUSS FYCE LACE LACK LACS LACY LAID LAIN LALL LANA LAND LANE LANK LARA LARD LARK LARS LASE LASH LASS LAST LATE LATH LATS LEAD LEAH LEAK LEAL LEAN LEAS LECH LEEK LEES LEET LEIA LEIS LELA LENA LEND LENS LENT LEON LESS LEST LETS LIAN LICE LICH LICK LIED LIEN LIES LILA LILT LILY LINA LINE LINK LINN LINS LINT LINY LION LIRA LIRE LISA LIST LITE LITS LOAD LOAN LOCA LOCH LOCK LOID LOIN LOLA LOLL LONE LOOK LOON LOOS LOOT LORD LORE LORN LORY LOSE LOSS LOST LOTA LOTH LOTS LUCA LUCE LUCK LUCY LUES LUIS LULL LUNA LUNE LUNK LUNT LUNY LURE LURK LUSH LUST LUTE LYCH LYES LYLA LYLE LYRA LYRE LYSE MACE MACH MACK MACS MACY MAES MAIA MAID MAIL MAIN MALE MALL MALT MANA MANE MANS MANY MARA MARE MARK MARL MARS MART MARY MASA MASH MASK MASS MAST MATE MATH MATS MATT MEAD MEAL MEAN MEAT MEED MEEK MEET MELD MELL MELS MELT MEND MERE MERK MERL MESA MESH MESS META METE METH MHOS MIAH MICA MICE MICK MICS MIEN MILA MILD MILE MILK MILL MILS MILT MINA MIND MINE MINK MINT MIRA MIRE MIRK MIRS MIRY MISE MISS MIST MITE MITT MITY MOAN MOAS MOAT MOCK MOCS MOIL MOLA MOLD MOLE MOLL MOLS MOLT MOLY MONA MONK MONS MONY MOOD MOOL MOON MOOS MOOT MORA MORE MORN MORS MORT MOSH MOSK MOSS MOST MOTE MOTH MOTS MOTT MUCH MUCK MULE MULL MUNS MUON MURA MURE MURK MUSA MUSE MUSH MUSK MUSS MUST MUTE MUTS MUTT MYAH MYCS MYLA MYNA MYRA MYTH PACA PACE PACK PACS PACT PACY PAID PAIK PAIL PAIN PALE PALL PALS PALY PANE PANS PANT PARA PARD PARE PARK PARS PART PASE PASH PASS PAST PATE PATH PATS PATY PEAK PEAL PEAN PEAS PEAT PECH PECK PECS PEED PEEK PEEL PEEN PEES PEIN PELE PELT PEND PENS PENT PEON PERE PERK PERT PEST PETS PHAT PHIS PHON PHOT PIAL PIAN PIAS PICA PICE PICK PICS PIED PIES PILE PILL PILY PINA PINE PINK PINS PINT PINY PION PIRN PISH PISS PITA PITH PITS PITY PLAN PLAT PLAY PLEA PLED PLIE PLOD PLOT PLOY POCK POET POIS POLE POLL POLS POLY POND PONE PONS PONY POOD POOH POOL POON POOS PORE PORK PORN PORT POSE POSH POST POSY POTS PRAT PRAY PREE PREY PROA PROD PROS PUCE PUCK PULA PULE PULL PULS PUNA PUNK PUNS PUNT PUNY PURE PURL PURS PUSH PUSS PUTS PUTT PYAS PYES PYIN PYRE SAAD SACK SACS SAID SAIL SAIN SALE SALL SALS SALT SANA SAND SANE SANK SANS SARA SARD SARK SASH SASS SATE SEAL SEAN SEAS SEAT SECS SECT SEED SEEK SEEL SEEN SEES SEIS SELL SELS SEND SENE SENT SERA SERE SERS SETA SETH SETS SETT SHAD SHAE SHAH SHAT SHAY SHEA SHED SHES SHIN SHIT SHOD SHOE SHOT SIAL SICE SICK SICS SILD SILK SILL SILT SINE SINH SINK SINS SIRE SIRS SITE SITH SITS SLAT SLAY SLED SLID SLIT SLOE SLOT SOAK SOCA SOCK SOIL SOLA SOLD SOLE SOLS SONE SONS SOOK SOON SOOT SORA SORD SORE SORN SORT SOTH SOTS SPAE SPAN SPAS SPAT SPAY SPED SPIK SPIN SPIT SPOT SPRY SRIS SUCH SUCK SUED SUES SUET SUIT SULK SUNK SUNN SUNS SURA SURD SURE SUSS SYCE SYED SYNE TACE TACH TACK TACT TAEL TAIL TAIN TALA TALE TALK TALL TANK TANS TAOS TARA TARE TARN TARS TART TASK TASS TATE TATS TEAK TEAL TEAS TEAT TECH TEED TEEL TEEN TEES TELA TELE TELL TELS TEND TENS TENT TERN TESS TEST TETH TETS THAE THAN THAT THEA THEE THEN THEY THIN THIS TICK TICS TIED TIES TILE TILL TILS TILT TINA TINE TINS TINT TINY TIRE TIRL TITS TOAD TOEA TOED TOES TOIL TOIT TOLA TOLD TOLE TOLL TONE TONS TONY TOOK TOOL TOON TOOT TORA TORE TORN TORS TORT TORY TOSH TOSS TOST TOTE TOTS TRAD TRAE TRAY TREE TREK TRES TRET TREY TROD TROT TROY TUCK TUIS TULE TUNA TUNE TUNS TURD TURK TURN TUSH TUSK TUTS TYCE TYEE TYES TYIN TYNE TYRE WACK WAES WAIL WAIN WAIT WALE WALK WALL WALY WAND WANE WANK WANS WANT WANY WARD WARE WARK WARN WARS WART WARY WASH WAST WATS WATT WEAK WEAL WEAN WEED WEEK WEEL WEEN WEES WEET WELD WELL WELT WEND WENS WENT WERE WERT WEST WETS WHAT WHEE WHEN WHET WHEY WHID WHIN WHIT WHOA WICH WICK WILD WILE WILL WILT WILY WIND WINE WINK WINS WINY WIRE WIRY WISE WISH WISS WIST WITE WITH WITS WOAD WOES WOLD WONK WONS WONT WOOD WOOL WOOS WORD WORE WORK WORN WORT WOST WOTS WREN WRIT WUSS WYCH WYES WYLE WYND WYNN WYNS WYTE\n"
     ]
    }
   ],
   "source": [
    "show(improved_lock(greedy_lock()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How about starting from a random lock? "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lock:  TMSLBPFWCD AEHYLORIWU CNATELISRO LDSYANKETH\n",
      "Count: 1240\n",
      "Words: BAAL BAAS BACH BACK BAIL BAIT BALD BALE BALK BALL BALS BAND BANE BANK BANS BARD BARE BARK BARN BARS BASE BASH BASK BASS BAST BATE BATH BATS BATT BEAD BEAK BEAN BEAT BECK BEEN BEES BEET BELL BELS BELT BEND BENE BENS BENT BERK BEST BETA BETH BETS BIAS BICE BILE BILK BILL BIND BINE BINS BINT BIOS BIRD BIRK BIRL BISE BISK BITE BITS BITT BLAE BLAH BLAT BLED BLET BLIN BLOT BOAS BOAT BOCK BOIL BOLA BOLD BOLE BOLL BOLT BOND BONE BONK BONY BOOK BOON BOOS BOOT BORA BORE BORK BORN BORT BOSH BOSK BOSS BOTA BOTH BOTS BOTT BRAD BRAE BRAN BRAS BRAT BRAY BREA BRED BREE BREN BRIA BRIE BRIN BRIS BRIT BROS BUCK BULK BULL BUNA BUND BUNK BUNN BUNS BUNT BUOY BURA BURD BURL BURN BURS BURY BUSH BUSK BUSS BUST BUSY BUTE BUTS BUTT BYES BYRE BYRL BYTE CACA CAEL CAID CAIN CALE CALK CALL CANE CANS CANT CARA CARD CARE CARK CARL CARN CARS CART CASA CASE CASH CASK CAST CATE CATS CECA CEES CEIL CELL CELS CELT CENT CERE CESS CETE CHAD CHAT CHAY CHIA CHID CHIN CHIS CHIT CHON CIAN CINE CION CIRE CIST CITE CITY CLAD CLAN CLAY CLOD CLON CLOT CLOY COAL COAT COCA COCK COED COEN COIL COIN COLA COLD COLE COLS COLT COLY CONE CONK CONN CONS CONY COOK COOL COON COOS COOT CORA CORD CORE CORK CORN CORS CORY COSH COSS COST COSY COTE COTS CRED CRIS CRIT CUED CUES CULL CULT CUNT CURD CURE CURL CURN CURS CURT CUSK CUSS CUTE CUTS CYAN CYST DACE DAIS DALE DALS DANA DANE DANK DANS DARE DARK DARN DART DASH DATA DATE DEAD DEAL DEAN DECK DEED DEES DEET DEIL DELE DELL DELS DELT DENE DENS DENT DENY DEON DERE DESK DHAK DHAL DIAL DICE DICK DIED DIEL DIES DIET DILL DINA DINE DINK DINS DINT DIOL DION DIRE DIRK DIRL DIRT DISH DISK DISS DITA DITE DITS DOAT DOCK DOCS DOES DOIT DOLE DOLL DOLS DOLT DONA DONE DONS DORE DORK DORS DORY DOSE DOSS DOST DOTE DOTH DOTS DOTY DRAT DRAY DREE DREK DUAD DUAL DUCE DUCK DUCT DUEL DUES DUET DUIT DULL DULY DUNE DUNK DUNS DUNT DUOS DURA DURE DURN DUSK DUST DUTY DYAD DYED DYES DYNE FACE FACT FAIL FAIN FALL FANE FANS FARD FARE FARL FART FASH FAST FATE FATS FEAL FEAT FECK FEED FEEL FEES FEET FELL FELT FEND FENS FEOD FERE FERN FESS FEST FETA FETE FETS FIAT FICE FILA FILE FILL FILS FIND FINE FINK FINN FINS FIRE FIRN FIRS FISH FIST FITS FLAK FLAN FLAT FLAY FLEA FLED FLEE FLEY FLIT FLOE FOAL FOES FOIL FOIN FOLD FOLK FOND FONS FONT FOOD FOOL FOOT FORA FORD FORE FORK FORT FOSS FRAE FRAT FRAY FRED FREE FRET FRIT FROE FUCK FUEL FULL FUND FUNK FUNS FURL FURS FURY FUSE FUSS FYCE LACE LACK LACS LACY LAID LAIN LALL LANA LAND LANE LANK LARA LARD LARK LARS LASE LASH LASS LAST LATE LATH LATS LEAD LEAH LEAK LEAL LEAN LEAS LECH LEEK LEES LEET LEIA LEIS LELA LENA LEND LENS LENT LEON LESS LEST LETS LIAN LICE LICH LICK LIED LIEN LIES LILA LILT LILY LINA LINE LINK LINN LINS LINT LINY LION LIRA LIRE LISA LIST LITE LITS LOAD LOAN LOCA LOCH LOCK LOID LOIN LOLA LOLL LONE LOOK LOON LOOS LOOT LORD LORE LORN LORY LOSE LOSS LOST LOTA LOTH LOTS LUCA LUCE LUCK LUCY LUES LUIS LULL LUNA LUNE LUNK LUNT LUNY LURE LURK LUSH LUST LUTE LYCH LYES LYLA LYLE LYRA LYRE LYSE MACE MACH MACK MACS MACY MAES MAIA MAID MAIL MAIN MALE MALL MALT MANA MANE MANS MANY MARA MARE MARK MARL MARS MART MARY MASA MASH MASK MASS MAST MATE MATH MATS MATT MEAD MEAL MEAN MEAT MEED MEEK MEET MELD MELL MELS MELT MEND MERE MERK MERL MESA MESH MESS META METE METH MHOS MIAH MICA MICE MICK MICS MIEN MILA MILD MILE MILK MILL MILS MILT MINA MIND MINE MINK MINT MIRA MIRE MIRK MIRS MIRY MISE MISS MIST MITE MITT MITY MOAN MOAS MOAT MOCK MOCS MOIL MOLA MOLD MOLE MOLL MOLS MOLT MOLY MONA MONK MONS MONY MOOD MOOL MOON MOOS MOOT MORA MORE MORN MORS MORT MOSH MOSK MOSS MOST MOTE MOTH MOTS MOTT MUCH MUCK MULE MULL MUNS MUON MURA MURE MURK MUSA MUSE MUSH MUSK MUSS MUST MUTE MUTS MUTT MYAH MYCS MYLA MYNA MYRA MYTH PACA PACE PACK PACS PACT PACY PAID PAIK PAIL PAIN PALE PALL PALS PALY PANE PANS PANT PARA PARD PARE PARK PARS PART PASE PASH PASS PAST PATE PATH PATS PATY PEAK PEAL PEAN PEAS PEAT PECH PECK PECS PEED PEEK PEEL PEEN PEES PEIN PELE PELT PEND PENS PENT PEON PERE PERK PERT PEST PETS PHAT PHIS PHON PHOT PIAL PIAN PIAS PICA PICE PICK PICS PIED PIES PILE PILL PILY PINA PINE PINK PINS PINT PINY PION PIRN PISH PISS PITA PITH PITS PITY PLAN PLAT PLAY PLEA PLED PLIE PLOD PLOT PLOY POCK POET POIS POLE POLL POLS POLY POND PONE PONS PONY POOD POOH POOL POON POOS PORE PORK PORN PORT POSE POSH POST POSY POTS PRAT PRAY PREE PREY PROA PROD PROS PUCE PUCK PULA PULE PULL PULS PUNA PUNK PUNS PUNT PUNY PURE PURL PURS PUSH PUSS PUTS PUTT PYAS PYES PYIN PYRE SAAD SACK SACS SAID SAIL SAIN SALE SALL SALS SALT SANA SAND SANE SANK SANS SARA SARD SARK SASH SASS SATE SEAL SEAN SEAS SEAT SECS SECT SEED SEEK SEEL SEEN SEES SEIS SELL SELS SEND SENE SENT SERA SERE SERS SETA SETH SETS SETT SHAD SHAE SHAH SHAT SHAY SHEA SHED SHES SHIN SHIT SHOD SHOE SHOT SIAL SICE SICK SICS SILD SILK SILL SILT SINE SINH SINK SINS SIRE SIRS SITE SITH SITS SLAT SLAY SLED SLID SLIT SLOE SLOT SOAK SOCA SOCK SOIL SOLA SOLD SOLE SOLS SONE SONS SOOK SOON SOOT SORA SORD SORE SORN SORT SOTH SOTS SRIS SUCH SUCK SUED SUES SUET SUIT SULK SUNK SUNN SUNS SURA SURD SURE SUSS SWAN SWAT SWAY SWOT SYCE SYED SYNE TACE TACH TACK TACT TAEL TAIL TAIN TALA TALE TALK TALL TANK TANS TAOS TARA TARE TARN TARS TART TASK TASS TATE TATS TEAK TEAL TEAS TEAT TECH TEED TEEL TEEN TEES TELA TELE TELL TELS TEND TENS TENT TERN TESS TEST TETH TETS THAE THAN THAT THEA THEE THEN THEY THIN THIS TICK TICS TIED TIES TILE TILL TILS TILT TINA TINE TINS TINT TINY TIRE TIRL TITS TOAD TOEA TOED TOES TOIL TOIT TOLA TOLD TOLE TOLL TONE TONS TONY TOOK TOOL TOON TOOT TORA TORE TORN TORS TORT TORY TOSH TOSS TOST TOTE TOTS TRAD TRAE TRAY TREE TREK TRES TRET TREY TROD TROT TROY TUCK TUIS TULE TUNA TUNE TUNS TURD TURK TURN TUSH TUSK TUTS TWAE TWAS TWAT TWEE TWIN TWIT TWOS TYCE TYEE TYES TYIN TYNE TYRE WACK WAES WAIL WAIN WAIT WALE WALK WALL WALY WAND WANE WANK WANS WANT WANY WARD WARE WARK WARN WARS WART WARY WASH WAST WATS WATT WEAK WEAL WEAN WEED WEEK WEEL WEEN WEES WEET WELD WELL WELT WEND WENS WENT WERE WERT WEST WETS WHAT WHEE WHEN WHET WHEY WHID WHIN WHIT WHOA WICH WICK WILD WILE WILL WILT WILY WIND WINE WINK WINS WINY WIRE WIRY WISE WISH WISS WIST WITE WITH WITS WOAD WOES WOLD WONK WONS WONT WOOD WOOL WOOS WORD WORE WORK WORN WORT WOST WOTS WREN WRIT WUSS WYCH WYES WYLE WYND WYNN WYNS WYTE\n"
     ]
    }
   ],
   "source": [
    "show(improved_lock(random_lock()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We got up to 1240 words, but can we go beyond?   I'll improve 50 random locks, taking 6000 steps each rather than just 3000 (this will take around 15 minutes):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 15min 48s, sys: 9.03 s, total: 15min 57s\n",
      "Wall time: 19min 40s\n"
     ]
    }
   ],
   "source": [
    "%time improved_locks = [improved_lock(random_lock(seed=i), 6000) for i in range(50)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see what we got:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Counter({1232: 3, 1235: 5, 1240: 42})"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Counter(map(word_count, improved_locks))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So 42/50 locks got a score of 1240.\n",
    "My first reaction to this was that if I discovered  42 different locks with score 1240, then probably there is at least one undiscovered lock with a score above 1240. But a discussion with [Matt Chisholm](https://blog.glyphobet.net/faq) changed my thinking. The key is to realize that some locks that look different are actually the same; they just have the letters in a different order. I define the function `alock` to put each tumbler into alphabetical order (and make the lock be a tuple rather than a list, so that it can be an entry in a `dict` or `set`):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def alock(lock):\n",
    "    \"Canonicalize lock by alphabetizing the letters in each tumbler.\"\n",
    "    return tuple(Tumbler(sorted(tumbler)) for tumbler in lock)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then we can find the unique locks:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{('BCDFHLMPST', 'AEHILORUWY', 'ACELMNORST', 'ADEKLNPSTY'): 1232,\n",
       " ('BCDFLMPSTW', 'AEHILOPRUY', 'ACEILNORST', 'ADEHKLNSTY'): 1240,\n",
       " ('BCDFLMPSTW', 'AEHILORUWY', 'ACEILNORST', 'ADEHKLNSTY'): 1240,\n",
       " ('BCDGLMPSTW', 'AEHILORUWY', 'AEILMNORST', 'ADEKLNPSTY'): 1235}"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def unique_locks(locks):\n",
    "    \"Return a dict of {lock: word_count} for the distinct locks.\"\n",
    "    return {alock(lock): word_count(lock) \n",
    "            for lock in locks}\n",
    "\n",
    "unique_locks(improved_locks)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So out of the 50 `improved_locks` there are actually only 4 distinct ones. And only two have a score of 1240:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{('BCDFLMPSTW', 'AEHILOPRUY', 'ACEILNORST', 'ADEHKLNSTY'),\n",
       " ('BCDFLMPSTW', 'AEHILORUWY', 'ACEILNORST', 'ADEHKLNSTY')}"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "peaks = {alock(lock) for lock in improved_locks if word_count(lock) == 1240}\n",
    "peaks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These two differ in just one letter (a `P` or a `W` in the second tumbler). \n",
    "\n",
    "This discovery changes my whole thinking about the space of scores for locks.  Previously I imagined a spiky \"porcupine-shaped\" landscape, with 42 different peaks hitting a height of 1240.  But now I have a different picture of the landscape: a single peak containing the two locks (one with a `P` and one with a `W`), surrounded by rolling hills. To verify this picture, I'll look at all the neighbors of the two peak locks, and see which ones are at least 1240:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{('BCDFLMPSTW', 'AEHILOPRUY', 'ACEILNORST', 'ADEHKLNSTY'): 1240,\n",
       " ('BCDFLMPSTW', 'AEHILORUWY', 'ACEILNORST', 'ADEHKLNSTY'): 1240}"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alphabetset = set(alphabet)\n",
    "\n",
    "def neighborhood(lock): \n",
    "    \"Yield all locks resulting from a change of one letter in one tumbler.\"\n",
    "    for i in range(len(lock)):\n",
    "        for new in alphabetset - set(lock[i]):\n",
    "            for old in lock[i]:\n",
    "                lock2 = Lock(lock)\n",
    "                lock2[i] = lock2[i].replace(old, new)\n",
    "                yield lock2\n",
    "                    \n",
    "unique_locks(lock for peak in peaks for lock in neighborhood(peak) if word_count(lock) >= 1240)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nothing new. This doesn't prove there is no lock with score over 1240, but it does mean we have looked hard to find one and failed.\n",
    "\n",
    "# Question 3: Simultaneous Words"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Can we make a lock that spells 10 words simultaneously?  One possible approach would be to start with any lock and randomly change it (just as we did with `improved_lock`), but measure improvements by the number of words formed. My intuition is that this approach would work, eventually, but that progress would be very slow, because most random changes to a letter would not make a word.\n",
    "\n",
    "An alternative approach is to think of the lock not as a list of 4 vertical tumblers (each with 10 letters), but rather as a list of 10 horizontal words (each with 4 letters). I'll call this the *word list* representation, and note that a lock and a word list are *[matrix transposes](http://en.wikipedia.org/wiki/Transpose)* of each other&mdash;they swap rows for columns. There is an [old trick](https://books.google.com/books?id=eH6jBQAAQBAJ&pg=PA574&lpg=PA574&dq=lisp+transpose+matrix&source=bl&ots=Yixwj8m3k4&sig=KoeuJnFhRnJsiD06_Cx56rUOetQ&hl=en&sa=X&ved=0CB4Q6AEwAGoVChMIyM-WiriLxgIVD6OICh2QcwBK#v=onepage&q=transpose%20matrix&f=false) to compute the transpose of a matrix `M` with the expression `zip(*M)`. But `zip` returns tuples; we want strings, so we can define `transpose` as:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def transpose(strings): return [Word(letters) for letters in zip(*strings)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And we can see the transpose of the `wordlock` is a list of words:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['SLED',\n",
       " 'PENS',\n",
       " 'HYMN',\n",
       " 'MHLM',\n",
       " 'TNRP',\n",
       " 'WRTY',\n",
       " 'DUAL',\n",
       " 'LOOK',\n",
       " 'FAST',\n",
       " 'BIKE']"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "transpose(['SPHMTWDLFB', \n",
    "           'LEYHNRUOAI', \n",
    "           'ENMLRTAOSK', \n",
    "           'DSNMPYLKTE'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first row of the word list has the letters SLED, because those are the letters in the first column of the lock.  You can see that the WordLock&reg; is designed to spell out LOOK FAST BIKE, among other words.\n",
    "\n",
    "Now we're ready to find a good word list with this strategy:\n",
    "\n",
    "1. Start with some word list (e.g., a random sample of 10 words from `WORDS`).\n",
    "2. Pick, at random, one word and change it to a new word.\n",
    "3. If the change is an improvement, keep the change; otherwise discard the change.\n",
    "4. Repeat.\n",
    "\n",
    "But what counts as an improvement?  We can't improve the number of words, because we start with 10 words, and every change also gives us 10 words. Rather, we will try to improve the number of duplicate letters on any tumbler (of the lock that corresponds to the word list). We improve by reducing the number of duplicate letters, and stop when there are no duplicates.\n",
    "\n",
    "The following code implements this approach:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def improved_wordlist(wordlist):\n",
    "    \"Find a wordlist that has no duplicate letters, via random changes to wordlist.\"\n",
    "    score = duplicates(wordlist)\n",
    "    while score > 0:\n",
    "        wordlist2 = changed_wordlist(wordlist)\n",
    "        score2 = duplicates(wordlist2)\n",
    "        if score2 < score:   \n",
    "            wordlist, score = wordlist2, score2\n",
    "    return wordlist\n",
    "    \n",
    "def duplicates(wordlist):\n",
    "    \"The number of duplicate letters across all the tumblers of the lock that corresponds to this wordlist.\"\n",
    "    lock = transpose(wordlist) \n",
    "    def duplicates(tumbler): return len(tumbler) - len(set(tumbler))\n",
    "    return sum(duplicates(tumbler) for tumbler in lock)\n",
    "\n",
    "def changed_wordlist(wordlist, words=list(WORDS)):\n",
    "    \"Make a copy of wordlist and replace one of the words.\"\n",
    "    copy    = list(wordlist)\n",
    "    i       = random.randrange(len(wordlist))\n",
    "    copy[i] = random.choice(words)\n",
    "    return copy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The structure of `improved_wordlist` is similar to `improved_lock`, with a few differences:\n",
    "1. We are minimizing duplicates, not maximizing word count. \n",
    "2. We stop when the score is 0, rather than continuing for a given number of iterations.\n",
    "3. We want to make a `random.choice` from `WORDS`.  But `random.choice` can't operate on a `set`, so we\n",
    "have to introduce `words=list(WORDS)`.\n",
    "\n",
    "Now we can find some wordlists:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['KNUR',\n",
       " 'FLAG',\n",
       " 'APES',\n",
       " 'EVIL',\n",
       " 'COZY',\n",
       " 'TICK',\n",
       " 'PHON',\n",
       " 'LATU',\n",
       " 'DUPE',\n",
       " 'REFT']"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "improved_wordlist(random.sample(WORDS, 10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That was easy!  Can we go to 11?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['BRAS',\n",
       " 'EMIR',\n",
       " 'NIPA',\n",
       " 'PESO',\n",
       " 'ONYX',\n",
       " 'WYNN',\n",
       " 'CUKE',\n",
       " 'MOLY',\n",
       " 'FLOC',\n",
       " 'THEM',\n",
       " 'HARL']"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "improved_wordlist(random.sample(WORDS, 11))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Improving Anything"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now have two similar functions, `improved_lock` and `improved_wordlist`.  Could (and should?) we replace them by a single function, say, `improved`, that could improve locks, wordlists, and anything else?\n",
    "\n",
    "The answer is: *yes* we could, and *maybe* we should.\n",
    "\n",
    "It is nice to form an abstraction for the idea of *improvement*.  (Traditionally, the method we have used for improvement has been called *hill-climbing*, because of the analogy that the score is like the elevation on a topological map, and we are trying to find our way to a peak.)\n",
    "\n",
    "However, there are many variations on the theme of *improvement*: maximizing or minimizing? Repeat for a given number of iterations, or continue until we meet a goal?  I don't want `improved` to have an argument list a mile long, and I felt that five arguments is right on the border of acceptable. The arguments are:\n",
    "1. `item`: The object to start with; this is what we will try to improve.\n",
    "2. `changed`: a function that generates a new item.\n",
    "3. `scorer`: a function that evaluates the quality of an item.\n",
    "4. `extremum`: should be `max` if we are maximizing scores, or `min` if we are minimizing scores.\n",
    "5. `stop`: a predicate with args `(i, score, item)`, where `i` is the iteration number, and `score` is `scorer(item)`. Return `True` to stop.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def improved(item, changed, scorer, extremum, stop):\n",
    "    \"\"\"Apply the function `changed` to `item` and evaluate with the function `scorer`;\n",
    "    When `stop(i, score)` is true, return `item`.\"\"\"\n",
    "    score = scorer(item)\n",
    "    for i in itertools.count(0):\n",
    "        if stop(i, score):\n",
    "            return item\n",
    "        item2  = changed(item)\n",
    "        score2 = scorer(item2)\n",
    "        if score2 == extremum(score, score2):\n",
    "            item, score = item2, score2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can re-implement `improved_lock` and `improved_wordlist` using `improved`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def improved_lock(lock, steps=3000):\n",
    "    \"Randomly change letters in lock, keeping changes that improve the score.\"\n",
    "    return improved(lock, changed_lock, word_count, max,\n",
    "                    lambda i, _: i == steps)\n",
    "\n",
    "def improved_wordlist(wordlist):\n",
    "    \"Find a wordlist that has no duplicate letters, via random changes to wordlist.\"\n",
    "    return improved(wordlist, changed_wordlist, duplicates, min,\n",
    "                    lambda _, score: score == 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lock:  TMSLBPFWCD AEHYLORIWU CNATELISRO LDSYANKETH\n",
      "Count: 1240\n",
      "Words: BAAL BAAS BACH BACK BAIL BAIT BALD BALE BALK BALL BALS BAND BANE BANK BANS BARD BARE BARK BARN BARS BASE BASH BASK BASS BAST BATE BATH BATS BATT BEAD BEAK BEAN BEAT BECK BEEN BEES BEET BELL BELS BELT BEND BENE BENS BENT BERK BEST BETA BETH BETS BIAS BICE BILE BILK BILL BIND BINE BINS BINT BIOS BIRD BIRK BIRL BISE BISK BITE BITS BITT BLAE BLAH BLAT BLED BLET BLIN BLOT BOAS BOAT BOCK BOIL BOLA BOLD BOLE BOLL BOLT BOND BONE BONK BONY BOOK BOON BOOS BOOT BORA BORE BORK BORN BORT BOSH BOSK BOSS BOTA BOTH BOTS BOTT BRAD BRAE BRAN BRAS BRAT BRAY BREA BRED BREE BREN BRIA BRIE BRIN BRIS BRIT BROS BUCK BULK BULL BUNA BUND BUNK BUNN BUNS BUNT BUOY BURA BURD BURL BURN BURS BURY BUSH BUSK BUSS BUST BUSY BUTE BUTS BUTT BYES BYRE BYRL BYTE CACA CAEL CAID CAIN CALE CALK CALL CANE CANS CANT CARA CARD CARE CARK CARL CARN CARS CART CASA CASE CASH CASK CAST CATE CATS CECA CEES CEIL CELL CELS CELT CENT CERE CESS CETE CHAD CHAT CHAY CHIA CHID CHIN CHIS CHIT CHON CIAN CINE CION CIRE CIST CITE CITY CLAD CLAN CLAY CLOD CLON CLOT CLOY COAL COAT COCA COCK COED COEN COIL COIN COLA COLD COLE COLS COLT COLY CONE CONK CONN CONS CONY COOK COOL COON COOS COOT CORA CORD CORE CORK CORN CORS CORY COSH COSS COST COSY COTE COTS CRED CRIS CRIT CUED CUES CULL CULT CUNT CURD CURE CURL CURN CURS CURT CUSK CUSS CUTE CUTS CYAN CYST DACE DAIS DALE DALS DANA DANE DANK DANS DARE DARK DARN DART DASH DATA DATE DEAD DEAL DEAN DECK DEED DEES DEET DEIL DELE DELL DELS DELT DENE DENS DENT DENY DEON DERE DESK DHAK DHAL DIAL DICE DICK DIED DIEL DIES DIET DILL DINA DINE DINK DINS DINT DIOL DION DIRE DIRK DIRL DIRT DISH DISK DISS DITA DITE DITS DOAT DOCK DOCS DOES DOIT DOLE DOLL DOLS DOLT DONA DONE DONS DORE DORK DORS DORY DOSE DOSS DOST DOTE DOTH DOTS DOTY DRAT DRAY DREE DREK DUAD DUAL DUCE DUCK DUCT DUEL DUES DUET DUIT DULL DULY DUNE DUNK DUNS DUNT DUOS DURA DURE DURN DUSK DUST DUTY DYAD DYED DYES DYNE FACE FACT FAIL FAIN FALL FANE FANS FARD FARE FARL FART FASH FAST FATE FATS FEAL FEAT FECK FEED FEEL FEES FEET FELL FELT FEND FENS FEOD FERE FERN FESS FEST FETA FETE FETS FIAT FICE FILA FILE FILL FILS FIND FINE FINK FINN FINS FIRE FIRN FIRS FISH FIST FITS FLAK FLAN FLAT FLAY FLEA FLED FLEE FLEY FLIT FLOE FOAL FOES FOIL FOIN FOLD FOLK FOND FONS FONT FOOD FOOL FOOT FORA FORD FORE FORK FORT FOSS FRAE FRAT FRAY FRED FREE FRET FRIT FROE FUCK FUEL FULL FUND FUNK FUNS FURL FURS FURY FUSE FUSS FYCE LACE LACK LACS LACY LAID LAIN LALL LANA LAND LANE LANK LARA LARD LARK LARS LASE LASH LASS LAST LATE LATH LATS LEAD LEAH LEAK LEAL LEAN LEAS LECH LEEK LEES LEET LEIA LEIS LELA LENA LEND LENS LENT LEON LESS LEST LETS LIAN LICE LICH LICK LIED LIEN LIES LILA LILT LILY LINA LINE LINK LINN LINS LINT LINY LION LIRA LIRE LISA LIST LITE LITS LOAD LOAN LOCA LOCH LOCK LOID LOIN LOLA LOLL LONE LOOK LOON LOOS LOOT LORD LORE LORN LORY LOSE LOSS LOST LOTA LOTH LOTS LUCA LUCE LUCK LUCY LUES LUIS LULL LUNA LUNE LUNK LUNT LUNY LURE LURK LUSH LUST LUTE LYCH LYES LYLA LYLE LYRA LYRE LYSE MACE MACH MACK MACS MACY MAES MAIA MAID MAIL MAIN MALE MALL MALT MANA MANE MANS MANY MARA MARE MARK MARL MARS MART MARY MASA MASH MASK MASS MAST MATE MATH MATS MATT MEAD MEAL MEAN MEAT MEED MEEK MEET MELD MELL MELS MELT MEND MERE MERK MERL MESA MESH MESS META METE METH MHOS MIAH MICA MICE MICK MICS MIEN MILA MILD MILE MILK MILL MILS MILT MINA MIND MINE MINK MINT MIRA MIRE MIRK MIRS MIRY MISE MISS MIST MITE MITT MITY MOAN MOAS MOAT MOCK MOCS MOIL MOLA MOLD MOLE MOLL MOLS MOLT MOLY MONA MONK MONS MONY MOOD MOOL MOON MOOS MOOT MORA MORE MORN MORS MORT MOSH MOSK MOSS MOST MOTE MOTH MOTS MOTT MUCH MUCK MULE MULL MUNS MUON MURA MURE MURK MUSA MUSE MUSH MUSK MUSS MUST MUTE MUTS MUTT MYAH MYCS MYLA MYNA MYRA MYTH PACA PACE PACK PACS PACT PACY PAID PAIK PAIL PAIN PALE PALL PALS PALY PANE PANS PANT PARA PARD PARE PARK PARS PART PASE PASH PASS PAST PATE PATH PATS PATY PEAK PEAL PEAN PEAS PEAT PECH PECK PECS PEED PEEK PEEL PEEN PEES PEIN PELE PELT PEND PENS PENT PEON PERE PERK PERT PEST PETS PHAT PHIS PHON PHOT PIAL PIAN PIAS PICA PICE PICK PICS PIED PIES PILE PILL PILY PINA PINE PINK PINS PINT PINY PION PIRN PISH PISS PITA PITH PITS PITY PLAN PLAT PLAY PLEA PLED PLIE PLOD PLOT PLOY POCK POET POIS POLE POLL POLS POLY POND PONE PONS PONY POOD POOH POOL POON POOS PORE PORK PORN PORT POSE POSH POST POSY POTS PRAT PRAY PREE PREY PROA PROD PROS PUCE PUCK PULA PULE PULL PULS PUNA PUNK PUNS PUNT PUNY PURE PURL PURS PUSH PUSS PUTS PUTT PYAS PYES PYIN PYRE SAAD SACK SACS SAID SAIL SAIN SALE SALL SALS SALT SANA SAND SANE SANK SANS SARA SARD SARK SASH SASS SATE SEAL SEAN SEAS SEAT SECS SECT SEED SEEK SEEL SEEN SEES SEIS SELL SELS SEND SENE SENT SERA SERE SERS SETA SETH SETS SETT SHAD SHAE SHAH SHAT SHAY SHEA SHED SHES SHIN SHIT SHOD SHOE SHOT SIAL SICE SICK SICS SILD SILK SILL SILT SINE SINH SINK SINS SIRE SIRS SITE SITH SITS SLAT SLAY SLED SLID SLIT SLOE SLOT SOAK SOCA SOCK SOIL SOLA SOLD SOLE SOLS SONE SONS SOOK SOON SOOT SORA SORD SORE SORN SORT SOTH SOTS SRIS SUCH SUCK SUED SUES SUET SUIT SULK SUNK SUNN SUNS SURA SURD SURE SUSS SWAN SWAT SWAY SWOT SYCE SYED SYNE TACE TACH TACK TACT TAEL TAIL TAIN TALA TALE TALK TALL TANK TANS TAOS TARA TARE TARN TARS TART TASK TASS TATE TATS TEAK TEAL TEAS TEAT TECH TEED TEEL TEEN TEES TELA TELE TELL TELS TEND TENS TENT TERN TESS TEST TETH TETS THAE THAN THAT THEA THEE THEN THEY THIN THIS TICK TICS TIED TIES TILE TILL TILS TILT TINA TINE TINS TINT TINY TIRE TIRL TITS TOAD TOEA TOED TOES TOIL TOIT TOLA TOLD TOLE TOLL TONE TONS TONY TOOK TOOL TOON TOOT TORA TORE TORN TORS TORT TORY TOSH TOSS TOST TOTE TOTS TRAD TRAE TRAY TREE TREK TRES TRET TREY TROD TROT TROY TUCK TUIS TULE TUNA TUNE TUNS TURD TURK TURN TUSH TUSK TUTS TWAE TWAS TWAT TWEE TWIN TWIT TWOS TYCE TYEE TYES TYIN TYNE TYRE WACK WAES WAIL WAIN WAIT WALE WALK WALL WALY WAND WANE WANK WANS WANT WANY WARD WARE WARK WARN WARS WART WARY WASH WAST WATS WATT WEAK WEAL WEAN WEED WEEK WEEL WEEN WEES WEET WELD WELL WELT WEND WENS WENT WERE WERT WEST WETS WHAT WHEE WHEN WHET WHEY WHID WHIN WHIT WHOA WICH WICK WILD WILE WILL WILT WILY WIND WINE WINK WINS WINY WIRE WIRY WISE WISH WISS WIST WITE WITH WITS WOAD WOES WOLD WONK WONS WONT WOOD WOOL WOOS WORD WORE WORK WORN WORT WOST WOTS WREN WRIT WUSS WYCH WYES WYLE WYND WYNN WYNS WYTE\n"
     ]
    }
   ],
   "source": [
    "show(improved_lock(random_lock()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['UMAR',\n",
       " 'DISH',\n",
       " 'TEMP',\n",
       " 'JUDE',\n",
       " 'WORM',\n",
       " 'STOW',\n",
       " 'BHUT',\n",
       " 'YAGI',\n",
       " 'ACTA',\n",
       " 'GYPS']"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "improved_wordlist(random.sample(WORDS, 10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Question 4: Coincidence?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There is still one unanswered question: did the designers of WordLock&reg; deliberately put  \"FRED BUNS\" in, or was it a coincidence? Hacker News reader [emhart](https://news.ycombinator.com/user?id=emhart) (aka the competitive lockpicker Schyler Towne) astutely commented that he had found the [patent](https://www.google.com/patents/US6621405) assigned to WordLock; it describes an algorithm similar to my `greedy_lock`.\n",
    "After seeing that, I'm inclined to believe that \"FRED BUNS\" is the coincidental result of running the algorithm. On\n",
    "the other hand, there is a [followup patent](https://www.google.com/patents/US20080053167) that discusses a refinement\n",
    "\"wherein the letters on the wheels are configured to spell a first word displayed on a first row of letters and a second word displayed on a second row of letters.\" So the possibility of a two-word phrase was somthing that Wordlock LLc. was aware of.\n",
    "\n",
    "We see below that the procedure described in the [patent](https://www.google.com/patents/US6621405) is not quite as good as `greedy_lock`, because the patent states that at each tumbler position \"*the entire word list is scanned*\" to produce the letter frequencies, whereas `greedy_lock` scans only the words that are consistent with the previous tumblers. Because of that difference, `greedy_lock` produces more words, 1177 to 1161:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1177, 1161)"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def greedy_lock_patented(t=4, c=10, words=WORDS):\n",
    "    \"Make a lock with t tumblers, each consisting of the c letters that cover the most words at that position.\"\n",
    "    lock = Lock()\n",
    "    for i in range(t):\n",
    "        # Make a tumbler of c letters, such that the tumbler covers the most words.\n",
    "        # Then update words to only include the ones that can be made with this tumbler\n",
    "        counter = Counter(word[i] for word in words)\n",
    "        tumbler = Tumbler(L for (L, _) in counter.most_common(c))\n",
    "        # words = [w for w in words if w[i] in tumbler] # <<<< The patent does not update the word list\n",
    "        lock.append(tumbler)\n",
    "    return lock\n",
    "\n",
    "word_count(greedy_lock()), word_count(greedy_lock_patented())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tests"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is a \n",
    "good idea to have some tests, in case you want to change some code and see if you have introduced an error. Also, tests serve as examples of usage of functions. The following tests have poor coverage, because it is hard to test non-deterministic functions, and I didn't attempt that here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'pass'"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def tests():\n",
    "    assert 'WORD' in WORDS\n",
    "    assert 'FRED' in WORDS\n",
    "    assert 'BUNS' in WORDS\n",
    "    assert 'XYZZ' not in WORDS\n",
    "    assert 'word' not in WORDS\n",
    "    assert 'FIVE' in WORDS\n",
    "    assert 'FIVER' not in WORDS\n",
    "    assert len(WORDS) == 4360\n",
    "    \n",
    "    assert fredbuns == ['FB', 'RU', 'EN', 'DS']\n",
    "    assert combinations(fredbuns) == ['FRED','FRES','FRND','FRNS','FUED','FUES','FUND','FUNS',\n",
    "                                      'BRED','BRES','BRND','BRNS','BUED','BUES','BUND','BUNS']\n",
    "    assert words_from(fredbuns) ==   ['FRED', 'FUND', 'FUNS', 'BRED', 'BUND', 'BUNS']\n",
    "    assert \"FRED\" in words_from(wordlock) and \"BUNS\" in words_from(wordlock)\n",
    "\n",
    "    assert wordlock == ['SPHMTWDLFB', 'LEYHNRUOAI', 'ENMLRTAOSK', 'DSNMPYLKTE']\n",
    "    assert len(combinations(wordlock)) == 10000\n",
    "    assert word_count(wordlock) == 1118\n",
    "    \n",
    "    assert transpose(['HIE', 'BYE']) == ['HB', 'IY', 'EE']\n",
    "    assert transpose(transpose(wordlock)) == wordlock\n",
    "    \n",
    "    return 'pass'\n",
    "    \n",
    "tests()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# One More Question"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "I wonder if [@BIKESNOBNYC](https://twitter.com/bikesnobnyc) would appreciate this notebook?  On the one hand, he is the kind of guy who, in discussing the fact that bicycling is the seventh most popular recreational activity,  [wrote]() \"*the number seven is itself a highly significant number. It is the lowest number that cannot be represented as the sum of the square of three integers*,\" so it seems he has some interest in mathematical oddities.  On the other hand, he followed that up by writing \"*I have no idea what that means, but it's true*,\" so maybe not."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{7, 15, 23, 28, 31, 39, 47, 55, 60, 63, 71, 79, 87, 92, 95}"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Numbers up to 100 that are not the sum of 3 squares\n",
    "nums = range(11)\n",
    "sums = {A**2 + B**2 + C**2 for A in nums for B in nums for C in nums}\n",
    "set(range(max(nums)**2)) - sums"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
